package com.seckill.trade.mq;

import com.seckill.api.dto.trade.OrderBasicDTO;
import com.seckill.common.utils.CollUtils;
import com.seckill.trade.domian.dto.SecOrderDTO;
import com.seckill.trade.domian.po.Order;
import com.seckill.trade.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.seckill.common.constants.MqConstants.Exchange.TRADE_DELAY_EXCHANGE;
import static com.seckill.common.constants.MqConstants.Exchange.TRADE_EXCHANGE;
import static com.seckill.common.constants.MqConstants.Key.ORDER_PAY_KEY;
import static com.seckill.common.constants.MqConstants.Key.SEC_KILL_KEY;


@Slf4j
@Component
public class OrderEventListener {

    @Autowired
    private IOrderService orderService;

    //监听订单支付消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.order.queue", durable = "true"),
            exchange = @Exchange(name = TRADE_DELAY_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_PAY_KEY
    ))
    public void listenOrderDelayMessage(Order order) {
        if (order == null || order.getUserId() == null) {
            log.debug("订单支付，异常消息，信息未空");
            return;
        }
        log.debug("处理订单支付消息：{}", order);
        // 1.查询订单
        Order oo = orderService.getById(order.getId());
        // 2.检测订单状态，判断是否已支付
        if(oo == null || oo.getStatus() != 1){
            // 订单不存在或者已经支付
            return;
        }
        // 3..未支付，取消订单，回复库存
        orderService.cancelOrder(oo.getId());
    }

    // 秒杀排队下单
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.order.sec.queue", durable = "true"),
            exchange = @Exchange(name = TRADE_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = SEC_KILL_KEY
    ))
    public void listenOrderSecMessage(SecOrderDTO secOrderDTO) {
        if (secOrderDTO == null || secOrderDTO.getUserId() == null) {
            log.debug("订单支付，异常消息，信息未空");
            return;
        }
        log.debug("处理秒杀订单消息：{}", secOrderDTO);
        orderService.processSecOrder(secOrderDTO);
    }
}
